﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Net.Mail;
using System.Threading;
using System.Web.Security;
using System.Web.Mvc;
using Yonkly.Fitlers;
using Yonkly.Models;
using Membership = System.Web.Security.Membership;
using System.ComponentModel;
using Yonkly.Utility;

namespace Yonkly.Controllers
{
    /// <summary>
    /// Base class which contains common stuffs.
    /// </summary>
    [LogFilter(Order = 1)]
    [ErrorFilter(Order = 2)]
    public abstract class BaseController : Controller
    {
        private static readonly string AdminEmail = ConfigurationManager.AppSettings["adminEmail"];
        private static readonly string AdminName = ConfigurationManager.AppSettings["adminName"];
        private readonly MembershipProvider _userManager;

        /// <summary>
        /// Gets the MembershipProvider.
        /// </summary>
        /// <value>The user manager.</value>
        protected MembershipProvider UserManager
        {
            //[DebuggerStepThrough]
            get { return _userManager; }
        }

        /// <summary>
        /// Gets a value indicating whether the currently visiting user is authenticated.
        /// </summary>
        /// <value>
        /// if user authenticated returns <c>true</c>; otherwise, <c>false</c>.
        /// </value>
        protected bool IsUserAuthenticated
        {
            //[DebuggerStepThrough]
            get { return HttpContext.User.Identity.IsAuthenticated; }
        }

        /// <summary>
        /// Gets the name of the current user. If the user is not authenticated it returns "Anonymous"
        /// </summary>
        /// <value>The name of the current user.</value>
        protected string LoggedInUserName
        {
            //[DebuggerStepThrough]
            get { return IsUserAuthenticated ? HttpContext.User.Identity.Name : string.Empty; }
        }

        private string LoggedInUserEmail
        {
            get { return IsUserAuthenticated ? UserManager.GetUser(LoggedInUserName, true).Email : string.Empty; }
        }

        /// <summary>
        /// Gets the current user id. if the user is not authenticated it returns empty guid.
        /// </summary>
        /// <value>The current user id.</value>
        internal protected Guid LoggedInUserId
        {
            //[DebuggerStepThrough]
            get
            {
                if (!IsUserAuthenticated)
                {
                    return Guid.Empty;
                }

                MembershipUser user = UserManager.GetUser(LoggedInUserName, true);

                return (Guid)user.ProviderUserKey;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseController"/> class.
        /// </summary>
        /// <param name="userManager">The membership provider.</param>
        protected BaseController(MembershipProvider userManager)
        {
            _userManager = userManager;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseController"/> class.
        /// </summary>
        protected BaseController()
            : this(Membership.Provider)
        {
        }

        protected static void SendMail(string to, string subject, string body)
        {
            try
            {
                var t1 = new Thread(SendMailAsync);
                t1.Start(new string[] { to, subject, body });
            }
            catch (Exception ex)
            {
                Utils.Log(ex);
            }
        }

        private static void SendMailAsync(object emailInfo)
        {
            try
            {

                var paramArray = emailInfo as string[];
                if (paramArray != null)
                {
                    var to = paramArray[0];
                    var subject = paramArray[1];
                    var body = paramArray[2];

                    using (MailMessage message = new MailMessage())
                    {
                        message.From = new MailAddress(AdminEmail,
                                                       AdminName);
                        message.To.Add(new MailAddress(to));
                        message.Subject = subject;
                        message.Body = body;
                        message.IsBodyHtml = false;

                        var mailClient = new SmtpClient();
                        mailClient.Send(message);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.Log(ex);
            }
        }

        protected BaseViewData GetBaseViewData()
        {
            var viewData = new BaseViewData();

            viewData.IsAuthenticated = IsUserAuthenticated;
            if (IsUserAuthenticated)
            {

                viewData.LoggedInUser = UserItem.CreateUserItem(LoggedInUserName);
                viewData.CurrentUser = viewData.LoggedInUser;


            }
            return viewData;
        }

        protected BaseViewData GetBaseViewData(string userName)
        {
            var viewdata = GetBaseViewData();
            if (!string.IsNullOrEmpty(userName))
            {
                if (viewdata.LoggedInUser == null || viewdata.LoggedInUser.UserName != userName)
                {
                    viewdata.CurrentUser = UserItem.CreateUserItem(userName);
                }
            }
            return viewdata;
        }


    }
}